from selenium import webdriver
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.baidu.com/")
time.sleep(2)

# 打印当前句柄
handler_1 = driver.window_handles
print(handler_1)

# 定位百度热搜的元素组，一次点击并打印当前句柄
elements = driver.find_elements(By.CSS_SELECTOR, "span[class=title-content-title]")
for ele in elements[:3]:
    ele.click()
    print(driver.window_handles)
    # time.sleep(1)

time.sleep(1)
# 切换进入正确的页面，通过句柄来切换
driver.switch_to.window(driver.window_handles[1])
driver.find_element(By.XPATH, "//p/a/em[text()='加快构建新发展格局']").click()

time.sleep(5)
driver.quit()